package com.linghang.back.service.impl;

import com.linghang.back.entity.Article;
import com.linghang.back.repository.ArticleRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import java.util.Optional;

/**
 * 文章处理服务
 * 使用独立事务处理单篇文章
 */
@Slf4j
@Service
public class ArticleProcessService {
    
    @Autowired
    private ArticleRepository articleRepository;
    
    /**
     * 使用独立事务处理单篇文章
     * 使用REQUIRES_NEW确保每篇文章在单独的事务中处理
     * @param articleData 文章数据
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public void processArticle(Map<String, Object> articleData) {
        String wechatArticleId = (String) articleData.get("wechatArticleId");
        
        // 检查文章是否已存在
        Optional<Article> existingArticle = articleRepository.findByWechatArticleId(wechatArticleId);
        
        if (existingArticle.isPresent()) {
            log.debug("文章已存在，跳过: {}", wechatArticleId);
            return;
        }
        
        // 创建新文章
        Article newArticle = new Article();
        
        // 处理标题，防止过长
        String title = (String) articleData.get("title");
        if (title != null && title.length() > 255) {
            title = title.substring(0, 252) + "...";
            log.warn("文章标题过长，已截断: {}", wechatArticleId);
        }
        newArticle.setTitle(title);
        
        // 处理作者，防止过长
        String author = (String) articleData.get("author");
        if (author != null && author.length() > 100) {
            author = author.substring(0, 97) + "...";
            log.warn("文章作者名过长，已截断: {}", wechatArticleId);
        }
        newArticle.setAuthor(author);
        
        // 处理摘要内容，如果超过500个字符则截断
        String digest = (String) articleData.get("digest");
        if (digest != null && digest.length() > 500) {
            digest = digest.substring(0, 497) + "...";
            log.warn("文章摘要过长，已截断: {}", wechatArticleId);
        }
        newArticle.setDigest(digest);
        
        // 处理封面URL，防止过长
        String coverUrl = (String) articleData.get("coverUrl");
        if (coverUrl != null && coverUrl.length() > 1000) {
            coverUrl = coverUrl.substring(0, 997) + "...";
            log.warn("文章封面URL过长，已截断: {}", wechatArticleId);
        }
        newArticle.setCoverUrl(coverUrl);
        
        newArticle.setContent((String) articleData.get("content"));
        
        // 处理类型，防止过长
        String type = (String) articleData.get("type");
        if (type != null && type.length() > 50) {
            type = type.substring(0, 47) + "...";
            log.warn("文章类型过长，已截断: {}", wechatArticleId);
        }
        newArticle.setType(type);
        
        newArticle.setWechatArticleId(wechatArticleId);
        
        // 处理微信URL，防止过长
        String wechatUrl = (String) articleData.get("wechatUrl");
        if (wechatUrl != null && wechatUrl.length() > 1000) {
            wechatUrl = wechatUrl.substring(0, 997) + "...";
            log.warn("文章微信URL过长，已截断: {}", wechatArticleId);
        }
        newArticle.setWechatUrl(wechatUrl);
        newArticle.setReadCount(0);
        
        // 设置其他字段
        if (articleData.containsKey("showCoverPic")) {
            newArticle.setShowCoverPic((Boolean) articleData.get("showCoverPic"));
        }
        if (articleData.containsKey("needOpenComment")) {
            newArticle.setNeedOpenComment((Boolean) articleData.get("needOpenComment"));
        }
        if (articleData.containsKey("onlyFansCanComment")) {
            newArticle.setOnlyFansCanComment((Boolean) articleData.get("onlyFansCanComment"));
        }
        if (articleData.containsKey("isDeleted")) {
            newArticle.setIsDeleted((Boolean) articleData.get("isDeleted"));
        }
        
        // 转换时间戳为LocalDateTime
        String updateTimeStr = (String) articleData.get("publishDate");
        try {
            long timestamp = Long.parseLong(updateTimeStr) * 1000; // 秒转毫秒
            LocalDateTime publishDate = Instant.ofEpochMilli(timestamp)
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime();
            newArticle.setPublishDate(publishDate);
        } catch (Exception e) {
            newArticle.setPublishDate(LocalDateTime.now());
            log.error("解析发布时间失败", e);
        }
        
        // 保存文章
        articleRepository.save(newArticle);
        log.info("成功同步文章: {}", newArticle.getTitle());
    }
}
